/**
 * 统一AI服务架构
 * 整合所有AI功能，提供统一的接口和服务
 */

import { config, AI_BASE_URL, API_BASE_URL } from './config'
import { realDataService } from './realData'
import { realAIService, MessageRole, ChatMessage as RealChatMessage } from './realAIService'

// AI服务类型定义
export type AIServiceType = 'hospital' | 'attraction' | 'advisor' | 'medical' | 'navigation'

// AI消息接口
export interface AIMessage {
  id: string
  type: 'user' | 'assistant' | 'system'
  content: string
  timestamp: Date
  serviceType?: AIServiceType
  metadata?: {
    intent?: string
    entities?: Array<{ type: string; value: string; confidence?: number }>
    suggestions?: string[]
    actions?: Array<{
      type: 'navigate' | 'info' | 'appointment' | 'emergency' | 'call'
      label: string
      data: any
    }>
    context?: Record<string, any>
  }
}

// AI请求接口
export interface AIRequest {
  message: string
  serviceType: AIServiceType
  context?: {
    userId?: string
    hospitalId?: string
    attractionId?: string
    location?: { lng: number; lat: number }
    history?: AIMessage[]
  }
  preferences?: {
    language?: string
    responseType?: 'text' | 'voice' | 'multimodal'
    maxResponseLength?: number
  }
}

// AI响应接口
export interface AIResponse {
  id: string
  content: string
  intent: string
  confidence: number
  entities: Array<{ type: string; value: string; confidence: number }>
  suggestions: string[]
  actions: Array<{
    type: string
    label: string
    data: any
    priority?: number
  }>
  metadata?: {
    processingTime?: number
    model?: string
    language?: string
    context?: Record<string, any>
  }
}

// 意图识别结果
export interface IntentAnalysis {
  intent: string
  confidence: number
  entities: Array<{ type: string; value: string; confidence: number }>
  context?: Record<string, any>
}

// AI服务配置
export interface AIServiceConfig {
  maxHistoryLength: number
  responseTimeout: number
  retryCount: number
  fallbackEnabled: boolean
  multimodal: boolean
  voiceEnabled: boolean
  language: string
}

class AIService {
  private config: AIServiceConfig
  private conversationHistory: Map<string, AIMessage[]> = new Map()
  private userPreferences: Map<string, any> = new Map()
  private knowledgeBase: Map<string, any> = new Map()

  constructor() {
    this.config = {
      maxHistoryLength: 50,
      responseTimeout: 30000,
      retryCount: 3,
      fallbackEnabled: true,
      multimodal: false,
      voiceEnabled: false,
      language: 'zh-CN'
    }
    
    this.initializeKnowledgeBase()
  }

  /**
   * 初始化知识库
   */
  private initializeKnowledgeBase() {
    // 医院知识库
    this.knowledgeBase.set('hospital', {
      departments: [
        {
          name: '急诊科',
          keywords: ['急诊', '紧急', '急救', '抢救'],
          info: '24小时急救服务，处理各类急诊病例',
          location: { lng: 120.1551, lat: 30.2741 },
          floor: 'L1',
          phone: '120'
        },
        {
          name: '内科',
          keywords: ['内科', '内分泌', '消化', '呼吸', '心内'],
          info: '诊治内科常见疾病，包括高血压、糖尿病等',
          location: { lng: 120.1552, lat: 30.2742 },
          floor: 'L2',
          phone: '0571-12345678'
        },
        {
          name: '外科',
          keywords: ['外科', '手术', '骨科', '普外'],
          info: '提供各类外科手术和治疗',
          location: { lng: 120.1553, lat: 30.2743 },
          floor: 'L3',
          phone: '0571-12345679'
        },
        {
          name: '儿科',
          keywords: ['儿科', '小儿', '儿童', '婴儿'],
          info: '专门针对儿童的医疗服务',
          location: { lng: 120.1554, lat: 30.2744 },
          floor: 'L2',
          phone: '0571-12345680'
        }
      ],
      facilities: [
        {
          name: '药房',
          keywords: ['药房', '取药', '买药'],
          info: '提供处方药和非处方药',
          location: { lng: 120.1559, lat: 30.2749 },
          floor: 'L1',
          hours: '7:30-21:00'
        },
        {
          name: '检验科',
          keywords: ['检验', '化验', '抽血'],
          info: '各类医学检验服务',
          location: { lng: 120.1560, lat: 30.2750 },
          floor: 'B1',
          hours: '7:00-17:00'
        }
      ]
    })

    // 医疗症状知识库
    this.knowledgeBase.set('symptoms', {
      '发热': {
        departments: ['内科', '急诊科'],
        urgency: 'medium',
        advice: '建议测量体温，如超过38.5°C或伴有其他症状请及时就医'
      },
      '胸痛': {
        departments: ['心内科', '急诊科'],
        urgency: 'high',
        advice: '胸痛可能是心脏问题，建议立即前往急诊科'
      },
      '腹痛': {
        departments: ['消化内科', '普外科'],
        urgency: 'medium',
        advice: '根据疼痛位置和性质，可能需要内科或外科诊治'
      }
    })

    // 景区知识库
    this.knowledgeBase.set('attraction', {
      facilities: [
        {
          name: '游客中心',
          keywords: ['游客中心', '咨询', '问讯'],
          info: '提供景区咨询和服务',
          location: { lng: 120.1565, lat: 30.2755 }
        },
        {
          name: '卫生间',
          keywords: ['卫生间', '厕所', 'WC'],
          info: '公共卫生间，无障碍设施齐全',
          locations: [
            { lng: 120.1566, lat: 30.2756 },
            { lng: 120.1567, lat: 30.2757 }
          ]
        }
      ],
      stores: [
        {
          name: 'KFC',
          keywords: ['肯德基', 'KFC', '汉堡'],
          business: 'restaurant',
          promotion: '新品上市，第二杯半价',
          location: { lng: 120.1563, lat: 30.2753 }
        }
      ]
    })
  }

  /**
   * 处理AI请求的主入口
   */
  async processRequest(request: AIRequest): Promise<AIResponse> {
    try {
      const startTime = Date.now()
      
      // 构建医疗上下文信息
      const contextInfo = this.buildMedicalContext(request)
      
      // 构建对话消息
      const messages: RealChatMessage[] = []
      
      // 添加历史消息
      if (request.context?.history && request.context.history.length > 0) {
        const recentHistory = request.context.history.slice(-6) // 最近6条消息
        for (const histMsg of recentHistory) {
          messages.push({
            role: histMsg.type === 'user' ? MessageRole.USER : MessageRole.ASSISTANT,
            content: histMsg.content
          })
        }
      }
      
      // 添加当前用户消息
      const userMessage = contextInfo ? `${contextInfo}\n\n用户问题：${request.message}` : request.message
      messages.push({
        role: MessageRole.USER,
        content: userMessage
      })

      // 调用真实AI服务
      console.log('🤖 调用真实AI服务:', {
        messages: messages.length,
        service: request.serviceType,
        user: request.context?.userId
      })
      
      const aiResponse = await realAIService.chat(messages, {
        sessionId: request.context?.userId || 'default',
        temperature: 0.7,
        maxTokens: 2000
      })

      console.log('✅ AI响应成功:', {
        provider: aiResponse.provider,
        model: aiResponse.model,
        length: aiResponse.content.length
      })

      // 简单意图分析（基于回复内容）
      const intent = this.extractIntentFromResponse(aiResponse.content, request.serviceType)
      
      // 构建统一响应格式
      const response: AIResponse = {
        id: aiResponse.id,
        content: aiResponse.content,
        intent: intent.intent,
        confidence: intent.confidence,
        entities: intent.entities,
        suggestions: this.generateSuggestions(intent.intent, request.serviceType),
        actions: this.generateActions(intent, request.context),
        metadata: {
          processingTime: Date.now() - startTime,
          model: aiResponse.model,
          provider: aiResponse.provider,
          language: request.preferences?.language || 'zh-CN',
          tokens: aiResponse.usage?.totalTokens
        }
      }
      
      // 更新对话历史
      this.updateConversationHistory(request, response)
      
      return response
      
    } catch (error) {
      console.error('❌ AI Service Error:', error)
      // 如果真实AI服务失败，降级到模拟服务
      return this.getFallbackWithSimulation(request)
    }
  }

  /**
   * 意图识别和实体提取
   */
  private async analyzeIntent(message: string, serviceType: AIServiceType, context?: any): Promise<IntentAnalysis> {
    const normalizedMessage = message.toLowerCase()
    
    // 基于关键词的意图识别
    const intents: Record<string, { keywords: string[]; priority: number }> = {
      'navigation': { keywords: ['在哪', '怎么走', '位置', '导航', '地址'], priority: 8 },
      'appointment': { keywords: ['预约', '挂号', '就诊', '看病'], priority: 9 },
      'symptom_consultation': { keywords: ['疼', '痛', '不舒服', '症状', '病'], priority: 10 },
      'facility_query': { keywords: ['卫生间', '厕所', '药房', '停车', 'ATM'], priority: 7 },
      'emergency': { keywords: ['急诊', '紧急', '急救', '120'], priority: 10 },
      'department_info': { keywords: ['科室', '医生', '专家'], priority: 6 },
      'store_query': { keywords: ['吃', '喝', '买', '店'], priority: 5 },
      'promotion': { keywords: ['活动', '优惠', '折扣', '特价'], priority: 4 },
      'general_info': { keywords: ['什么', '介绍', '了解'], priority: 3 }
    }

    let bestIntent = 'general_info'
    let bestScore = 0
    let entities: Array<{ type: string; value: string; confidence: number }> = []

    // 计算意图得分
    for (const [intent, config] of Object.entries(intents)) {
      let score = 0
      for (const keyword of config.keywords) {
        if (normalizedMessage.includes(keyword)) {
          score += config.priority
        }
      }
      if (score > bestScore) {
        bestScore = score
        bestIntent = intent
      }
    }

    // 实体提取
    entities = this.extractEntities(normalizedMessage, serviceType)

    return {
      intent: bestIntent,
      confidence: Math.min(bestScore / 10, 1.0),
      entities,
      context: context
    }
  }

  /**
   * 实体提取
   */
  private extractEntities(message: string, serviceType: AIServiceType): Array<{ type: string; value: string; confidence: number }> {
    const entities: Array<{ type: string; value: string; confidence: number }> = []
    
    if (serviceType === 'hospital') {
      const hospitalData = this.knowledgeBase.get('hospital')
      
      // 提取科室实体
      for (const dept of hospitalData.departments) {
        for (const keyword of dept.keywords) {
          if (message.includes(keyword)) {
            entities.push({
              type: 'department',
              value: dept.name,
              confidence: 0.9
            })
            break
          }
        }
      }
      
      // 提取设施实体
      for (const facility of hospitalData.facilities) {
        for (const keyword of facility.keywords) {
          if (message.includes(keyword)) {
            entities.push({
              type: 'facility',
              value: facility.name,
              confidence: 0.9
            })
            break
          }
        }
      }
    }

    return entities
  }

  /**
   * 生成AI响应
   */
  private async generateResponse(request: AIRequest, analysis: IntentAnalysis): Promise<AIResponse> {
    const { intent, entities, confidence } = analysis
    let content = ''
    let suggestions: string[] = []
    let actions: any[] = []

    switch (request.serviceType) {
      case 'hospital':
        const result = this.generateHospitalResponse(intent, entities, request.message)
        content = result.content
        suggestions = result.suggestions
        actions = result.actions
        break
        
      case 'attraction':
        const attractionResult = this.generateAttractionResponse(intent, entities, request.message)
        content = attractionResult.content
        suggestions = attractionResult.suggestions
        actions = attractionResult.actions
        break
        
      case 'advisor':
        content = await this.generateAdvisorResponse(request.context)
        break
        
      default:
        content = '抱歉，我暂时无法处理这个请求。'
    }

    return {
      id: `ai_${Date.now()}`,
      content,
      intent,
      confidence,
      entities: entities || [],
      suggestions,
      actions
    }
  }

  /**
   * 生成医院相关响应
   */
  private generateHospitalResponse(intent: string, entities: any[], message: string) {
    const hospitalData = this.knowledgeBase.get('hospital')
    let content = ''
    let suggestions: string[] = []
    let actions: any[] = []

    switch (intent) {
      case 'navigation':
      case 'department_info':
        const deptEntity = entities.find(e => e.type === 'department')
        if (deptEntity) {
          const dept = hospitalData.departments.find((d: any) => d.name === deptEntity.value)
          if (dept) {
            content = `🏥 ${dept.name}\n\n📍 位置：${dept.floor}楼\n📞 电话：${dept.phone}\n\nℹ️ ${dept.info}`
            actions.push({
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: dept.location
            }, {
              type: 'appointment',
              label: '📅 预约挂号',
              data: dept
            })
            suggestions = ['预约挂号', '查看专家', '了解更多']
          }
        } else {
          content = '请告诉我您要找的科室名称，我来为您导航和介绍。'
          suggestions = ['急诊科在哪', '内科位置', '外科怎么走']
        }
        break

      case 'facility_query':
        const facilityEntity = entities.find(e => e.type === 'facility')
        if (facilityEntity) {
          const facility = hospitalData.facilities.find((f: any) => f.name === facilityEntity.value)
          if (facility) {
            content = `🏢 ${facility.name}\n\n📍 位置：${facility.floor}楼\n⏰ 服务时间：${facility.hours}\n\nℹ️ ${facility.info}`
            actions.push({
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: facility.location
            })
          }
        }
        break

      case 'symptom_consultation':
        content = this.generateSymptomAdvice(message)
        suggestions = ['我要挂号', '了解科室', '急诊科在哪']
        break

      case 'emergency':
        content = '🚨 紧急情况请立即前往急诊科！\n\n📍 位置：医院一楼东侧\n📞 急救电话：120\n\n⚡ 24小时急救服务'
        actions.push({
          type: 'navigate',
          label: '🚨 前往急诊科',
          data: { lng: 120.1551, lat: 30.2741 }
        }, {
          type: 'call',
          label: '📞 拨打120',
          data: { phone: '120' }
        })
        break

      default:
        content = '您好！我是医院智能助手，可以帮您导航科室、预约挂号、咨询症状等。请问需要什么帮助？'
        suggestions = ['急诊科在哪', '我要挂号', '头痛挂什么科']
    }

    return { content, suggestions, actions }
  }

  /**
   * 生成景区相关响应
   */
  private generateAttractionResponse(intent: string, entities: any[], message: string) {
    let content = ''
    let suggestions: string[] = []
    let actions: any[] = []

    // 景区响应逻辑
    switch (intent) {
      case 'navigation':
        content = '请告诉我您要去的具体位置，我来为您导航。'
        suggestions = ['卫生间在哪', '游客中心', '停车场位置']
        break
        
      case 'store_query':
        content = '为您推荐附近的餐饮和购物：\n\n🍗 KFC - 新品第二杯半价\n☕ 星巴克 - 季节特饮\n🏪 便利店 - 24小时服务'
        suggestions = ['查看优惠', '导航过去', '了解更多']
        break
        
      default:
        content = '您好！我是景区智能助手，可以为您提供导航、推荐和咨询服务。'
        suggestions = ['景区介绍', '美食推荐', '设施查询']
    }

    return { content, suggestions, actions }
  }

  /**
   * 生成运营顾问响应
   */
  private async generateAdvisorResponse(context?: any): Promise<string> {
    const realTimeData = realDataService.getAllRealTimeData()
    
    return `📊 实时运营分析：

🏥 当前状态：
• 总接诊量：${realTimeData.kpis.patientCount?.value || 0}人
• 平均等待时间：${realTimeData.kpis.avgWaitTime?.value || 0}分钟
• 床位使用率：${realTimeData.kpis.bedUtilization?.value || 0}%

⚠️ 关键指标：
• 高负载科室：${realTimeData.departments.filter((d: any) => d.utilizationRate >= 90).length}个
• 设备维护中：${realTimeData.equipment.filter((e: any) => e.status === 'maintenance').length}台

💡 建议优化措施：
• 调配人员至高负载科室
• 优化患者分流
• 加强设备维护管理`
  }

  /**
   * 生成症状建议
   */
  private generateSymptomAdvice(message: string): string {
    const symptoms = this.knowledgeBase.get('symptoms')
    
    for (const [symptom, info] of Object.entries(symptoms)) {
      if (message.includes(symptom)) {
        const symptomInfo = info as any
        return `💊 症状分析：${symptom}\n\n🏥 建议科室：${symptomInfo.departments.join('、')}\n\n⚠️ 紧急程度：${symptomInfo.urgency === 'high' ? '高' : symptomInfo.urgency === 'medium' ? '中' : '低'}\n\n💡 建议：${symptomInfo.advice}`
      }
    }
    
    return '根据您的症状描述，建议您先挂内科进行初步检查，医生会根据情况为您转诊到相应专科。'
  }

  /**
   * 更新对话历史
   */
  private updateConversationHistory(request: AIRequest, response: AIResponse) {
    const sessionId = request.context?.userId || 'default'
    
    if (!this.conversationHistory.has(sessionId)) {
      this.conversationHistory.set(sessionId, [])
    }
    
    const history = this.conversationHistory.get(sessionId)!
    
    // 添加用户消息
    history.push({
      id: `user_${Date.now()}`,
      type: 'user',
      content: request.message,
      timestamp: new Date(),
      serviceType: request.serviceType
    })
    
    // 添加AI响应
    history.push({
      id: response.id,
      type: 'assistant',
      content: response.content,
      timestamp: new Date(),
      serviceType: request.serviceType,
      metadata: {
        intent: response.intent,
        suggestions: response.suggestions,
        actions: response.actions
      }
    })
    
    // 限制历史长度
    if (history.length > this.config.maxHistoryLength) {
      history.splice(0, history.length - this.config.maxHistoryLength)
    }
  }

  /**
   * 获取fallback响应
   */
  private getFallbackResponse(request: AIRequest): AIResponse {
    return {
      id: `fallback_${Date.now()}`,
      content: '抱歉，我遇到了一些技术问题。请稍后再试，或者联系客服获得帮助。',
      intent: 'fallback',
      confidence: 0,
      entities: [],
      suggestions: ['重试', '联系客服', '返回主页'],
      actions: []
    }
  }

  /**
   * 获取对话历史
   */
  getConversationHistory(sessionId: string): AIMessage[] {
    return this.conversationHistory.get(sessionId) || []
  }

  /**
   * 清空对话历史
   */
  clearConversationHistory(sessionId: string) {
    this.conversationHistory.delete(sessionId)
  }

  /**
   * 更新用户偏好
   */
  updateUserPreferences(userId: string, preferences: any) {
    this.userPreferences.set(userId, { ...this.userPreferences.get(userId), ...preferences })
  }

  /**
   * 获取用户偏好
   */
  getUserPreferences(userId: string) {
    return this.userPreferences.get(userId) || {}
  }

  /**
   * 构建医疗上下文信息
   */
  private buildMedicalContext(request: AIRequest): string {
    let context = ''
    
    // 添加服务类型上下文
    switch (request.serviceType) {
      case 'hospital':
        context += '当前场景：医院数字孪生系统\n'
        context += '你需要帮助用户进行医院导航、科室查询、症状咨询等服务。\n'
        break
      case 'medical':
        context += '当前场景：医疗咨询服务\n'
        context += '你需要提供专业的医疗建议，但请提醒用户这不能替代专业医生的诊断。\n'
        break
      case 'attraction':
        context += '当前场景：景区服务\n'
        context += '你需要帮助游客进行景区导航、景点介绍、活动推荐等服务。\n'
        break
    }
    
    // 添加位置信息
    if (request.context?.location) {
      context += `当前位置：经度${request.context.location.lng}，纬度${request.context.location.lat}\n`
    }
    
    // 添加医院信息
    if (request.context?.hospitalId) {
      context += `当前医院ID：${request.context.hospitalId}\n`
    }
    
    return context
  }

  /**
   * 从AI回复中提取意图
   */
  private extractIntentFromResponse(content: string, serviceType: AIServiceType): IntentAnalysis {
    // 基础意图关键词匹配
    const intentKeywords = {
      'navigation': ['导航', '路线', '怎么走', '在哪里', '位置'],
      'info': ['是什么', '介绍', '信息', '详情', '说明'],
      'appointment': ['预约', '挂号', '就诊', '看病'],
      'emergency': ['急诊', '紧急', '救护', '急救'],
      'symptoms': ['症状', '不舒服', '疼痛', '发烧', '咳嗽'],
      'facilities': ['设施', '服务', '科室', '部门']
    }
    
    let bestIntent = 'info'
    let maxMatches = 0
    
    for (const [intent, keywords] of Object.entries(intentKeywords)) {
      const matches = keywords.filter(keyword => content.includes(keyword)).length
      if (matches > maxMatches) {
        maxMatches = matches
        bestIntent = intent
      }
    }
    
    return {
      intent: bestIntent,
      confidence: maxMatches > 0 ? 0.8 : 0.5,
      entities: []
    }
  }

  /**
   * 降级到模拟服务的Fallback
   */
  private async getFallbackWithSimulation(request: AIRequest): Promise<AIResponse> {
    console.log('🔄 降级到模拟AI服务')
    
    try {
      // 使用原来的模拟逻辑
      const analysis = await this.analyzeIntent(request.message, request.serviceType, request.context)
      const response = await this.generateResponse(request, analysis)
      
      response.metadata = {
        ...response.metadata,
        model: 'fallback-simulation',
        fallback: true
      }
      
      return response
    } catch (error) {
      return this.getFallbackResponse(request)
    }
  }
}

// 导出单例实例
export const aiService = new AIService()

// 导出快捷方法
export const processAIRequest = (request: AIRequest) => aiService.processRequest(request)
export const getAIHistory = (sessionId: string) => aiService.getConversationHistory(sessionId)
export const clearAIHistory = (sessionId: string) => aiService.clearConversationHistory(sessionId)

export default aiService